Intermediate Python

String formatting

Being able to print things to the screen is a fundamental part of interacting with a programming language. So far, we've kept it simple by passing the data we want to print directly to the print function:

format.py
my_num = 42

print(my_num)
$
python format.py
42

We made things a bit nicer by using the fact that if you pass multiple arguments to print then it will print each of them, separated by spaces, allowing us to combine our data with a message:

format.py
my_num = 42

print("My num is", my_num)
$
python format.py
My num is 42

This works perfectly well but firstly you're using the implicit space that's added by print as part of your sentence and secondly you're passing in two separate pieces of information where they are logically one.

What we can do instead is create a single string which contains the message we want to print and put special placeholders inside it where we want our data to appear. There's a few different ways to do this in Python (an older but still valid method you may see uses % and another uses a format() function) but for this course we will use the method called f-strings which was introduced in Python 3.6 (released December 2016).

If you put a single f directly in front of the string that you are creating, it will enable a special string mode which lets you place {} inside the string with a variable name between the { and the }:

format.py
my_num = 42

print(f"My num is {my_num}")
$
python format.py
My num is 42

You can have as many interpolations as you like:

format.py
answer = 42
pi = 3.14159

print(f"The answer is {answer} and pi is {pi}")
$
python format.py
The answer is 42 and pi is 3.14159

Exercise

For all the exercises in this course, we are going to be working on some Python code which converts to and from Morse Code. In each section we will add or change the code so make sure that you don't skip any exercises.

  • Copy the following code in the text editor into a script called encode.py and run it in the terminal with python encode.py to check that it works.

    letter_to_morse = {
        'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 
        'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 
        'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
        'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
        '0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
        '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', ' ':'/'
    }
    
    message = "please help"
    
    # `morse` is a list which will eventually contain the 
    # strings for each morse code letter in the message.
    morse = []
    
    for letter in message:
        morse_letter = letter_to_morse[letter]
        morse.append(morse_letter)
    
    # We need to join together Morse code letters with spaces
    morse_message = " ".join(morse)
    
    print(f"Incoming message: {message}")
    print(f"   Morse encoded: {morse_message}")
    
  • If you get an error when running the code, first check that you have saved the file encode.py.
  • If you get an error like SyntaxError: invalid syntax then try running the script with python3 encode.py.
  • answer